import React, { useMemo, useRef } from "react";
import { Space, Badge } from "antd";

import { helper } from '@yaf/utils';
import { ProTable, type TableType, type IProTableRef } from "@yaf/pro-ui";
import { useThemeToken, getEnv } from "@/constants";

import { getDataAction, CreateOrEdit, getFilterItems } from './proTableDriver';
import { RespDataType } from './api';
import { EditDictDataBtn } from './btns';

const List: React.FC = () => {
  const { themeToken } = useThemeToken();
  const proTableRef = useRef<IProTableRef>();
  const columns = useMemo(() => getColumns(), []);

  return (
    <ProTable
      ref={proTableRef}
      dataAction={getDataAction(proTableRef)}
      rowKey={"dictId"}
      theme={themeToken.proTableToken}
      headerProps={{
        operatorProps: {
          btnList: [
            { innerType: "create" },
            { innerType: "edit" },
            { innerType: "delete" }
          ],
          createOrEditProps: {
            modalProps: {
              width: "45%"
            },
            CreateOrEditContent: CreateOrEdit,
            getModalTitle: (rowKey) => rowKey ? "编辑字典类型" : "创建字典类型",
          },
        },
        filterProps: {
          maxWidth: "60%",
          filterItems: getFilterItems(),
        }
      }}
      contentProps={{
        tableProps: {
          columns,
        }
      }}
      onError={(msg) => console.error(msg)}
    />
  )
}

export default List;

const getColumns = () => {
  const { commonStatusList } = getEnv().globalConfig;
  const statusToInfo = helper.convertArrayToObj(commonStatusList);

  const columns: TableType.ColumnsType<RespDataType.DictItem> = [
    {
      title: '字典编号',
      dataIndex: 'dictId',
    },
    {
      title: '字典名称',
      dataIndex: 'dictName',
    },
    {
      title: '字典类型',
      dataIndex: 'dictType',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (value) => statusToInfo[value] ? <Badge color={statusToInfo[value].color} text={statusToInfo[value].label} /> : "-",
    },
    {
      title: '备注',
      dataIndex: 'remark',
      render: (text) => text ?? "-"
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      render: (text) => text ?? "-"
    },
    {
      title: "操作",
      render: (_, record) => <Space>
        <EditDictDataBtn dictName={record.dictName} dictId={record.dictId} dictType={record.dictType} />
      </Space>
    }
  ];

  return columns;
}
